import { getMongoRepository, ObjectID } from 'typeorm';

import { Messages } from '../models/Message';

class MessageService {
  // 查找双方共同的最后一条消息（多数据查询）
  findLastMsg(uid: string, fid: string) {
    const messageRepository = getMongoRepository(Messages)
    return messageRepository.findOne({
      where: {
        $or: [
          { uid, fid },
          { uid: fid, fid: uid }
        ]
      },
      // 倒序（降序）
      order: { time: 'DESC' }
    })
  }
  
  // 插入消息
  saveMsg(message: Messages) {
    const messageRepository = getMongoRepository(Messages)
    return messageRepository.save(message)
  }

  // 分页查询双方的聊天消息（多数据查询）
  findMsg(uid: string, fid: string, skipNum: number, limit: number) {
    const messageRepository = getMongoRepository(Messages)
    return messageRepository.find({
      where: {
        $or: [
          { uid, fid },
          { uid: fid, fid: uid }
        ]
      },
      skip: skipNum,
      take: limit,
      order: { time: 'DESC' }
    })
  }

  // 双方的聊天信息数量
  async findMsgCount(uid: string, fid: string) {
    const messageRepository = getMongoRepository(Messages)
    const [msg, count] = await messageRepository.findAndCount({
      where: {
        $or: [
          { uid, fid },
          { uid: fid, fid: uid }
        ]
      }
    })
    return count
  }

  // 根据 用户id和好友id，查询未读的消息和消息未读数（多数据查询）
  findUnReadMsgs(uid: string, fid: string) {
    const messageRepository = getMongoRepository(Messages)
    return messageRepository.findAndCount({
      where: {
        $and: [
          { uid: fid, fid: uid },
          { state: false}
        ]
      }
    })
  }

  // 查询自己是否有未读消息
  findUnReadMsg(uid: string) {
    const messageRepository = getMongoRepository(Messages)
    return messageRepository.findOne({fid: uid, state: false})
  }
}

export default new MessageService()